package com.example.java_chatroom.controller;

import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

@Component
//Component可以注册到spring里面
public class TestWebSocketController extends TextWebSocketHandler {
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
//        1、这个方法会在websocket连接建立成功后，被自动调用
//        super.afterConnectionEstablished(session);
        System.out.println("TestController连接成功");
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        //2、这个方法会在websocket收到消息后，被自动调用
//        super.handleTextMessage(session, message);
        System.out.println("TestController收到消息"+message.toString());
//        session是个会话，里面记录了通信双方是谁，session里面持有了websocket的通信连接
        session.sendMessage(message);
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
//        这个方法是在连接出现异常的时候，被自动调用的
//        super.handleTransportError(session, exception);
        System.out.println("TestController连接异常"+exception.toString());
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
//        这个方法是正常关闭后被调用
//        super.afterConnectionClosed(session, status);
        System.out.println("TestController连接关闭"+status.toString());
    }
}
